package com.my.wechat.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.my.wechat.domain.vo.WeChatMediaVO;
import com.sskj.core.annotation.ControllerLogExeTime;
import com.sskj.sys.domain.entity.MediaEntity;
import com.sskj.sys.repository.MediaRepository;

@RestController
@RequestMapping("/wechat/upload")
public class WeChatUploadMediaServiceImpl {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	MediaRepository mediaRepository;

	@Value("${sskj.conf.fileUploadPath}")
	private String fileUploadPath;

	@SuppressWarnings("static-access")
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/uploadMedia", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "上传媒体数据")
	public String uploadImg(WeChatMediaVO wcmv, HttpServletRequest request) {
		String fileBase64 = wcmv.getMedataBase64();
		fileBase64 = fileBase64.substring(fileBase64.indexOf("base64,") + 7, fileBase64.length());
		String path = request.getSession().getServletContext().getRealPath(fileUploadPath);
		logger.info(path);
		String name = String.valueOf(System.currentTimeMillis());
		String filename = name + "." + wcmv.getMediaSuffix();
		File targetFile = new File(path);
		// 生成图片保存的最终路径
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = null;
		String mediaId = "";
		Base64 base64 = new Base64();
		try {
			// //Base64解码
			byte[] bytes = base64.decodeBase64(new String(fileBase64).getBytes());

			ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			out = new FileOutputStream(path + filename);
			byte[] buffer = new byte[1024];
			int byteread = 0;
			long alreadyRead = 0;
			int waitTime = 500;
			long daoTime = System.currentTimeMillis() + waitTime;
			request.getSession().setAttribute("uploadProgress", "0%");
			logger.info("进入了这里");
			while ((byteread = in.read(buffer)) != -1) {
				alreadyRead += byteread;
				if (System.currentTimeMillis() > daoTime) {
					logger.info("文件总大小：" + bytes.length + ",已经写入：" + alreadyRead + ",完成了"
							+ (alreadyRead / bytes.length * 100) + "%");
					request.getSession().setAttribute("uploadProgress", (alreadyRead / bytes.length * 100) + "%");
					daoTime = System.currentTimeMillis() + waitTime;
				}
				out.write(buffer, 0, byteread); // 文件写操作
				out.flush();
			}
			out.close();
			request.getSession().setAttribute("uploadProgress", "100%");
			logger.info("文件总大小：" + bytes.length + ",已经写入：" + alreadyRead + ",完成了" + (alreadyRead / bytes.length * 100)
					+ "%");

			// 将信息写入媒体entity
			MediaEntity wme = new MediaEntity();
			wme.setMedianame(name);
			wme.setMediasuffix(wcmv.getMediaSuffix());
			wme.setMediatype("image");
			wme.setMediasize(bytes.length);
			wme.setMediaurl(path);
			wme.setAssociatedentity("DengGuangZhuShouEntity");
			wme.setCreatorId("Admin");
			mediaRepository.save(wme);
			mediaId = wme.getId();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mediaId;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/getMediaUploader", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "获取上传进度")
	public Map<String, Object> getMediaUploader(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String progress = (String) request.getSession().getAttribute("uploadProgress");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("progress", progress);
		return map;
	}

}
